import { Toast } from 'vant'
import router from '@/router'

const coursesModule = {
  namespaced: true,
  state: {
    courses: [],
    collection: [],
  },
  getters: {
    list: (state) => state.courses,
    noPay: (state) =>
      state.courses.filter((item) => item.orderStatus === '未支付'),
    finish: (state) =>
      state.courses.filter((item) => item.orderStatus === '已完成'),
    close: (state) =>
      state.courses.filter(
        (item) =>
          (item.orderStatus === '已关闭') | (item.orderStatus === '支付失败')
      ),
    collection: (state) => state.collection,
  },
  mutations: {
    /**
     *点击详情页立即购买添加课程
     * @param {*} state
     * @param {*} payload
     */
    addToDetail(state, payload) {
      const has = state.courses.find((cour) => cour.id === payload.id)
      if (has) {
        Toast('请不要重复添加订单')
        setTimeout(() => {
          router.push('/order')
        }, 1000)
      } else {
        state.courses.push({
          ...payload,
          orderStatus: '未支付',
        })
        router.push({
          path: '/confirm',
          query: payload,
        })
      }
    },
    /**
     * 支付状态修改为支付失败
     * @param {*} state
     * @param {*} payload
     */
    reviseOrderStatusFail(state, payload) {
      const has = state.courses.find((cour) => cour.id === payload.id)
      if (has) {
        has.orderStatus = '支付失败'
      }
    },
    /**
     * 支付状态修改为支付失败
     * @param {*} state
     * @param {*} payload
     */
    reviseOrderStatusSucceed(state, payload) {
      const has = state.courses.find((cour) => cour.id === payload.id)
      if (has) {
        has.orderStatus = '已完成'
      }
    },

    /**
     * 关闭订单
     * @param {*} state
     * @param {*} payload
     */
    deleteOrder(state, payload) {
      const has = state.courses.find((cour) => cour.id === payload)
      if (has) {
        has.orderStatus = '已关闭'
      }
    },
    /**
     * 加入收藏课程
     * @param {*} state
     * @param {*} payload
     */
    addToCollection(state, payload) {
      const has = state.collection.find((cour) => cour.id === payload.id)
      if (has) {
        Toast('请不要重复加入收藏')
      } else {
        state.collection.push({
          ...payload,
          collectionStatus: '收藏成功',
        })
      }
    },
    /**
     * 课程取消收藏
     * @param {*} state
     * @param {*} payload
     */
    deleteToCollection(state, payload) {
      state.Collection = state.Collection.filter(
        (cour) => cour.id !== payload.id
      )
    },
  },

  actions: {},
}
export default coursesModule
